package common;



import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

//公共
public class Utils {
    public static WebDriver driver;  //创建驱动对象

    //创建驱动对象
    public static WebDriver createDriver(){
        if (driver == null){
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            //允许访问所有链接
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            //隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
        }
        return driver;
    }

    //构造函数
    public Utils(String url){
        driver = createDriver();
        driver.get(url);
    }

    //屏幕截图方法
    public void getScreenShot(String str) throws IOException {
        //./src/test/image
        //2024-04-12
        //test01-18:23:87.png
        //test02-453563.png
        //创建格式
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");
        String dirTime = sim1.format(System.currentTimeMillis());
        String  fileTime = sim2.format(System.currentTimeMillis());

        String fileName = "./src/test/image/"+dirTime+"/"+str + "-" +fileTime +".png";
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(fileName)); //把原文件放到指定文件
    }


}
